<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Controllers\AdminController;
use App\Jobs\SetAdminLog;
use App\Models\Shop\Goods;
use App\Models\Shop\GoodsClassify;
use App\Models\Shop\Store;
use App\Models\Shop\StoreGoods;
use Carbon\Carbon;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\DB;

class StoreGoodsController extends AdminController
{
    /**
     * 验证条件数组
     * @var array
     */
    protected $verifyFactor = [
        'storeID'           =>  'required',
        'goodsID'           =>  'required|array',
        'number'            =>  'required|numeric'
    ];

    public function getIndex(Request $request)
    {
        $storeGoods = DB::table('shop_store_goods')
            ->join('shop_goods', 'shop_store_goods.goodsID', '=', 'shop_goods.id');
        if($request->has('goodsClassify'))
        {
            $storeGoods = $storeGoods->where('shop_goods.classifyID', $request->input('goodsClassify'));
        }
        if($request->has('storeID'))
        {
            $storeGoods = $storeGoods->where('shop_store_goods.storeID', $request->input('storeID'));
        }
        $storeGoods = $storeGoods->select('shop_store_goods.id', 'shop_store_goods.storeID', 'shop_store_goods.amount', 'shop_store_goods.realAmount', 'shop_store_goods.number', 'shop_store_goods.display',
                'shop_goods.classifyID', 'shop_goods.title', 'shop_goods.thumb')
            ->paginate(20);
        //获取商品分类
        $goodsClassify = GoodsClassify::all()->keyBy('id');
        //获取商店
        $store = Store::all()->keyBy('id');
        return view('admin.shop.storeGoods')->with(['storeGoods' => $storeGoods, 'goodsClassify' => $goodsClassify, 'store' => $store]);
    }

    /**
     * 添加
     * @return $this
     */
    public function getAdd()
    {
        //获取商品
        $goods = Goods::orderBy('id', 'desc')->get(['id','classifyID','title','price'])->keyBy('id');
        //获取店铺
        $store = Store::orderBy('id', 'desc')->get(['id','name'])->keyBy('id');
        //获取分类
        $goodsClassify = GoodsClassify::orderBy('id', 'desc')->get(['id','name'])->keyBy('id');
        return view('admin.shop.storeGoods-add')->with(['goods' => $goods, 'store' => $store, 'goodsClassify' => $goodsClassify]);
    }
    public function postAdd(Request $request)
    {
        //验证
        $verifyMsg = $this->verification($request->input());
        if(!$request->has('goodsID'))
        {
            $verifyMsg->merge(['goodsID' => ['请选择至少一个产品']]);
        }
        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\StoreGoodsController@getAdd')->withInput()->withErrors($verifyMsg);
        }
        $display = 0;
        if($request->has('display'))
            $display = 1;
        //整理数据
        foreach ($request->input('goodsID') as $k=>$v)
        {
            $arr = explode('-', $v);
            $data[$k] = [
                'storeID'       =>  $request->input('storeID'),
                'goodsID'       =>  $arr[0],
                'amount'        =>  $arr[1],
                'realAmount'    =>  $arr[1],
                'number'        =>  $request->input('number'),
                'display'       =>  $display
            ];
        }
        //需要插入的总数
        $sum = count($data);
        $n = 0;
        foreach ($data as $d)
        {
            if(!StoreGoods::where('storeID', $d['storeID'])->where('goodsID', $d['goodsID'])->first())
            {
                if(StoreGoods::create($d))
                    $n++;
            }
        }
        //Create
        if (($sum - $n) < $sum)
        {
            //setLog
            $this->setLog('create', NULL, json_encode($data));
            return ShowMsg('success', '成功添加 '.$n.'条数据，'.($sum - $n).'条重复', action('Admin\Shop\StoreGoodsController@getIndex'), 1);
        }

        return ShowMsg('error', getLang('Tips', 'createFail'), action('Admin\Shop\StoreGoodsController@getIndex'), 1);
    }

    /**
     * 修改补货
     * @param $id
     * @return $this
     */
    public function getEdit($id)
    {
        //获取店铺产品信息
        $storeGoods = DB::table('shop_store_goods')
            ->join('shop_goods', 'shop_store_goods.goodsID', '=', 'shop_goods.id')
            ->join('shop_store', 'shop_store_goods.storeID', '=', 'shop_store.id')
            ->where('shop_store_goods.id', $id)
            ->select('shop_store_goods.id', 'shop_store_goods.storeID', 'shop_store_goods.goodsID', 'shop_store_goods.amount', 'shop_store_goods.realAmount', 'shop_store_goods.number', 'shop_store_goods.display',
                'shop_goods.classifyID', 'shop_goods.title', 'shop_goods.thumb',
                'shop_store.name')
            ->first();
        return view('admin.shop.storeGoods-edit')->with(['storeGoods' => $storeGoods]);
    }
    public function postEdit(Request $request, $id)
    {
        //验证
        $this->verifyFactor['realAmount'] = 'required|numeric';
        $this->verifyFactor['addNumber'] = 'integer';
        $verifyMsg = $this->verification($request->input());
        if ($verifyMsg)
        {
            return redirect()->action('Admin\Shop\StoreGoodsController@postEdit', ['id' => $id])->withInput()->withErrors($verifyMsg);
        }
        //整理数据
        $display = 0;
        if($request->has('display'))
            $display = 1;
        $data = [
            'realAmount'        =>  $request->input('realAmount'),
            'display'           =>  $display
        ];
        //修改前的值
        $origin = StoreGoods::find($id)->toArray();
        //增加数目
        $checkAdd = false;
        if ($request->input('addNumber') > 0)
            $checkAdd = StoreGoods::where('id', $id)->increment('number', $request->input('addNumber'));
        //Update
        if (StoreGoods::where('id', $id)->update($data) || $checkAdd)
        {
            //setLog
            $data['addNumber'] = $request->input('addNumber');
            $this->setLog('update', json_encode($origin), json_encode($data));
            return ShowMsg('success', getLang('Tips', 'updateSuccess'), action('Admin\Shop\StoreGoodsController@getEdit', ['id' => $id]), 1);
        }
        return ShowMsg('error', getLang('Tips', 'updateFail'), action('Admin\Shop\StoreGoodsController@getEdit', ['id' => $id]), 1);

    }

    /**
     * 删除
     * @param $id
     * @return $this
     */
    public function getDel($id)
    {
        //获取商品
        $goods = StoreGoods::find($id);
        $origin = $goods->toArray();
        if (!empty($goods))
        {
            if ($goods->delete())
            {
                //setLog
                $this->setLog('delete', json_encode($origin));
                return ShowMsg('success', getLang('Tips', 'deleteSuccess'),'',1);
            }
        }
        return ShowMsg('error', getLang('Tips', 'illegal'),'',1);
    }

    /**
     * Ajax是否显示
     * @param Request $request
     * @return string
     */
    public function postDisplay(Request $request)
    {
        $storeGoods = StoreGoods::find($request->input('id'));
        if(!empty($storeGoods))
        {
            $origin = $storeGoods->toArray();
            $storeGoods->display = $request->input('display');
            if ($storeGoods->save())
            {
                //setLog
                $this->setLog('show', json_encode($origin), json_encode($request->except('_token')));
                return json_encode([
                    'code'      =>  1,
                    'message'   =>  getLang('Tips', 'updateSuccess')
                ]);
            }
        }
        return json_encode([
            'code'      =>  0,
            'message'   =>  getLang('Tips', 'updateFail')
        ]);
    }

    /**
     * 记录日志
     * @param string$type 类型 create update delete
     * @param json null $origin 事件发生前
     * @param json null $ending 事件发生后
     */
    private function setLog($type, $origin = NULL, $ending = NULL)
    {
        switch ($type)
        {
            case 'create':
                $event = [
                    'msg'   =>  'shop_store_goods.create',
                    'type'  =>  'Create'
                ];
                break;
            case 'update':
                $event = [
                    'msg'   =>  'shop_store_goods.update',
                    'type'  =>  'Update'
                ];
                break;
            case 'delete':
                $event = [
                    'msg'   =>  'shop_store_goods.delete',
                    'type'  =>  'Delete'
                ];
                break;
            case 'show':
                $event = [
                    'msg'   =>  'shop_store_goods.show',
                    'type'  =>  'Update'
                ];
                break;
        }
        //push to queue
        $geoIP = geoip()->getLocation();
        $this->dispatch(new SetAdminLog($this->user->id, $geoIP, $event['msg'], Carbon::now(), $event['type'], $origin, $ending));
    }
}
